//
//  InfoShareView.m
//  P2P
//
//  Created by wujiandong on 15/12/28.
//  Copyright (c) 2015年 EIMS. All rights reserved.
//

#import "InfoShareView.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <ShareSDK/ShareSDK.h>
#import <MessageUI/MessageUI.h>
#import <MailConnection/MailConnection.h>

#define kShareTag       100
#define kShareMoreTag   200
#define kLineNum        4
@interface InfoShareView () {
    double originY;
    
    UIView *_backView;
    NSMutableArray *_shareImageArray;
    NSMutableArray *_shareTitleArray;
    UIColor *_superViewColor;
}
@end

@implementation InfoShareView

- (id)initWithFrame:(CGRect)frame {
    
    if (self = [super initWithFrame:frame]) {
        originY = self.frame.origin.y;
        [self initData];
        [self initView];
    }
    return self;
}

- (void)dealloc {
    //[self cancelButtonClick];
    _backView = nil;
}

- (void)cancel {
    [self cancelButtonClick];
}

- (void)dealShareMoreTap:(UITapGestureRecognizer *)tap {
    
    NSInteger index = tap.view.tag - kShareMoreTag;
    if ([_shareTitleArray[index] isEqualToString:@"微信"] || [_shareTitleArray[index] isEqualToString:@"朋友圈"]) {
        if (![WXApi isWXAppInstalled]) {
            [SVProgressHUD showErrorWithStatus:@"您尚未安装该应用"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"QQ"] || [_shareTitleArray[index] isEqualToString:@"QQ空间"]) {
        if (![QQApiInterface isQQInstalled]) {
            [SVProgressHUD showErrorWithStatus:@"您尚未安装该应用"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"短信"]) {
        // 判断用户设备能否发送短信
        if (![MFMessageComposeViewController canSendText]) {
            [SVProgressHUD showErrorWithStatus:@"该设备不支持发送短信"];
            return;
        }
    }
    if ([_shareTitleArray[index] isEqualToString:@"邮件"]) {
        // 1. 先判断能否发送邮件
        if (![MFMailComposeViewController canSendMail]) {
            // 提示用户设置邮箱
            [SVProgressHUD showErrorWithStatus:@"该设备不支持邮件分享或尚未设置邮件帐号"];
            return;
        }
    }
    
    ShareType shareType = ShareTypeWeixiSession;
    switch (index) {
        case 0:
            shareType = ShareTypeWeixiSession;
            break;
        case 1:
            shareType = ShareTypeWeixiTimeline;
            break;
        case 2:
        {
            shareType = ShareTypeOther;
        }
            break;
        case 3:
            shareType = ShareTypeQQ;
            break;
        case 4:
            shareType = ShareTypeSinaWeibo;
            break;
        case 5:
            shareType = ShareTypeQQSpace;
            break;
        case 6:
            shareType = ShareTypeSMS;
            break;
        case 7:
            shareType = ShareTypeMail;
            break;
            
        default:
            shareType = ShareTypeWeixiSession;
            break;
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(shareMoreViewDidSelectWithShareType:)]) {
        [self.delegate shareMoreViewDidSelectWithShareType:shareType];
    }else {
        [self shareDataWithShareType:shareType];
    }
}


- (void)shareDataWithShareType:(ShareType)shareType {
    
    [AppDelegateInstance.window sendSubviewToBack:self];
    //构造分享内容
    NSString *url;
    if (self.shareUrl.length > 0) {
        url = self.shareUrl;
    }else {
        url = Baseurl;
    }
    
    id<ISSContent> publishContent;
    if (self.shareImage.length > 0) {
        publishContent = [ShareSDK content:self.shareContent
                            defaultContent:@"随取宝app全新面世!随存随取 8秒注册赢好礼!"
                                     image:[ShareSDK imageWithUrl:self.shareImage]
                                     title:self.shareTitle
                                       url:url
                               description:self.shareDescription
                                 mediaType:SSPublishContentMediaTypeNews];
    }else {
        publishContent = [ShareSDK content:self.shareContent
                            defaultContent:@"随取宝app全新面世!随存随取 8秒注册赢好礼!"
                                     image:[ShareSDK pngImageWithImage:[UIImage imageNamed:@"logo"]]
                                     title:self.shareTitle
                                       url:url
                               description:self.shareDescription
                                 mediaType:SSPublishContentMediaTypeNews];
    }
    
    
    [ShareSDK shareContent:publishContent
                      type:shareType
               authOptions:nil
              shareOptions:nil
             statusBarTips:YES
                    result:^(ShareType type, SSResponseState state,
                             id<ISSPlatformShareInfo> statusInfo, id<ICMErrorInfo> error, BOOL end) {
                        if (state == SSResponseStateSuccess) {
                            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"分享成功", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_SUC", @"分享成功"));
                            [self cancelButtonClick];
                        }else if (state == SSResponseStateFail) {
                            [AppDelegateInstance.window bringSubviewToFront:self];
                            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"分享失败", nil)];
                            DLOG(NSLocalizedString(@"TEXT_ShARE_FAI", @"分享失败,错误码:%d,错误描述:%@"), [error errorCode], [error errorDescription]);
                        }else {
                            [AppDelegateInstance.window bringSubviewToFront:self];
                        }
                    }];
}

- (void)cancelButtonClick {
    [UIView animateWithDuration:0.3 animations:^{
        _backView.frame = CGRectMake(0, self.frame.size.height, self.frame.size.width, 238);
        self.alpha = 0;
        [AppDelegateInstance.window bringSubviewToFront:self];
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

- (void)show {
    
    [UIView animateWithDuration:0.3 animations:^{
        _backView.frame = CGRectMake(0, self.frame.size.height - 238, self.frame.size.width, 238);
        self.alpha = 1;
        [AppDelegateInstance.window bringSubviewToFront:self];
    } completion:^(BOOL finished) {
    }];
}

- (void)initData {
    //    _shareImageArray = [[NSMutableArray alloc] initWithArray:@[@"Share_WeChat",@"Share_WeChat_Circle",@"Share_QQ",@"Share_QQZone",@"Share_WeiBo",@"Share_Message"]];
    //    _shareTitleArray = [[NSMutableArray alloc] initWithArray:@[@"微信",@"朋友圈",@"QQ好友",@"QQ空间",@"微博",@"短信"]];
    _shareImageArray = [[NSMutableArray alloc] initWithArray:@[@"Share_WeChat",@"Share_WeChat_Circle",@"Share_Code",@"Share_QQ",@"Share_WeiBo",@"Share_QQZone",@"Share_Message",@"Share_Mail"]];
    _shareTitleArray = [[NSMutableArray alloc] initWithArray:@[@"微信",@"朋友圈",@"二维码",@"QQ",@"微博",@"QQ空间",@"短信",@"邮件"]];
}

- (void)initView {
    
    self.frame = CGRectMake(0, 0, AppDelegateInstance.window.bounds.size.width, AppDelegateInstance.window.bounds.size.height);
    [AppDelegateInstance.window addSubview:self];
    
    UIView *cancelView = [UIView viewWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height - 238) backgroundColor:nil superview:self];
    [cancelView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancelButtonClick)]];
    
    _backView = [UIView viewWithFrame:CGRectMake(0, self.frame.size.height, self.frame.size.width, 238) backgroundColor:SETCOLOR(234, 235, 236, 1.0) superview:self];
    _backView.superview.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    
    [UIView viewWithFrame:CGRectMake(0, 0, self.frame.size.width, kLineHeight) backgroundColor:KlayerBorder superview:_backView];
    
    UILabel *shareValue = [UILabel labelWithFrame:CGRectMake(10, 10, self.frame.size.width - 20, 20) text:@"分享给好友" textColor:[ColorTools colorWithHexString:@"#3a3a3a"] textFont:13.0 fitWidth:NO superview:_backView];
    shareValue.textAlignment = NSTextAlignmentCenter;
    
    for (NSInteger i=0; i < _shareImageArray.count; i++) {
        double w = _backView.frame.size.width/kLineNum;
        double h = (238 - 48 - 60)/2;
        double x = (i%kLineNum) * w;
        double y = 48 + (i/kLineNum) * h;
        
        UIView *backView = [UIView viewWithFrame:CGRectMake(x, y, w, h) backgroundColor:nil superview:_backView];
        backView.tag = kShareMoreTag + i;
        [backView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dealShareMoreTap:)]];
        
        UIImageView *imageView = [UIImageView imageViewWithFrame:CGRectMake((backView.frame.size.width - 36)/2, 0, 36, 36) imageFile:_shareImageArray[i] superview:backView];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.userInteractionEnabled = YES;
        
        UILabel *label = [UILabel labelWithFrame:CGRectMake(10, CGRectGetMaxY(imageView.frame), backView.frame.size.width - 20, 20) text:_shareTitleArray[i] textColor:KBlackColor textFont:10.0 fitWidth:NO superview:backView];
        label.textAlignment = NSTextAlignmentCenter;
        label.userInteractionEnabled = YES;
        
        if ([_shareTitleArray[i] isEqualToString:@"微信"] || [_shareTitleArray[i] isEqualToString:@"朋友圈"]) {       //微信
            if (![WXApi isWXAppInstalled]) {
                label.textColor = KGrayColor;
            }
        }
        if ([_shareTitleArray[i] isEqualToString:@"QQ"] || [_shareTitleArray[i] isEqualToString:@"QQ空间"]) {
            if (![QQApiInterface isQQInstalled]) {
                label.textColor = KGrayColor;
            }
        }
    }
    
    UIButton *button =  [UIButton buttonWithFrame:CGRectMake(10, _backView.frame.size.height - 10 - 40, _backView.frame.size.width - 20, 40) backgroundColor:[UIColor whiteColor] title:@"取消" titleColor:KBlackColor titleFont:15.0 target:self action:@selector(cancelButtonClick) superview:_backView];
    [button setTitleColor:KGrayColor forState:UIControlStateHighlighted];
    button.clipsToBounds = YES;
    button.layer.cornerRadius = 3.0f;
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
